package com.anlu.concurrent.ch3;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * <p>
 * Description: 带版本戳的原子操作类
 * <p>
 * Copyright: 天津联想协同科技有限公司
 * <p>
 *
 * @author anlu
 * @date 2021/9/7 15:54
 */
public class UseAtomicStampedReference {
    static AtomicStampedReference<String> asr = new AtomicStampedReference<>("dd",0);

    public static void main(String[] args) throws InterruptedException{
        // 初始的版本号
        final int oldStamp = asr.getStamp();
        final String oldReferenc = asr.getReference();

        System.out.println(oldReferenc+"==============="+oldStamp);
        Thread rightStampThread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName()
                        +"当前变量值："+oldReferenc+" 当前版本戳："+oldStamp+"-"
                        +asr.compareAndSet(oldReferenc, oldReferenc+"Java",
                        oldStamp, oldStamp+1));

            }
        });

        Thread errorStampThread = new Thread(new Runnable() {
            @Override
            public void run() {
                String reference = asr.getReference();
                System.out.println(Thread.currentThread().getName()
                        +"当前变量值："+reference+" 当前版本戳："+asr.getStamp()+"-"
                        +asr.compareAndSet(reference, reference+"C",
                        oldStamp, oldStamp+1));
            }
        });

        rightStampThread.start();
        rightStampThread.join();

        errorStampThread.start();
        errorStampThread.join();
        System.out.println(asr.getReference()+"==========="+asr.getStamp());



    }


}
